// upload-file.js
Component({
  properties: {
    modelValue: { type: Array, optionalTypes: [String, Object], value: [] },
    action: { type: String, value: '/common/upload' },
    data: { type: Object, value: {} },
    limit: { type: Number, value: 5 },
    fileSize: { type: Number, value: 5 },
    fileType: { type: Array, value: () => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf'] },
    isShowTip: { type: Boolean, value: true },
    disabled: { type: Boolean, value: false }
  },

  data: {
    fileList: [],
    baseUrl: 'https://your-api-domain.com', // 替换为实际API域名
    uploadFileUrl: '',
    headers: {},
    showTip: true,
    maxSize: 5 * 1024 * 1024, // 5MB
    acceptType: 'file'
  },

  observers: {
    'modelValue': function(val) {
      this.setData({ fileList: this.formatFileList(val) });
    }
  },

  created() {
    const token = wx.getStorageSync('token') || '';
    this.setData({
      uploadFileUrl: this.data.baseUrl + this.properties.action,
      headers: { Authorization: `Bearer ${token}` },
      showTip: this.properties.isShowTip && (this.properties.fileType.length > 0 || this.properties.fileSize > 0),
      maxSize: this.properties.fileSize * 1024 * 1024
    });
  },

  methods: {
    formatFileList(value) {
      if (!value) return [];
      const list = Array.isArray(value) ? value : value.split(',');
      return list.map((item, index) => {
        if (typeof item === 'string') {
          return { name: item, url: item, uid: `file-${Date.now()}-${index}` };
        }
        return { ...item, uid: item.uid || `file-${Date.now()}-${index}` };
      });
    },

    // 文件读取前的校验
    beforeRead(event) {
      const { file, callback } = event.detail;
      const { fileType, fileSize } = this.properties;
      
      // 文件类型校验
      if (fileType.length) {
        const ext = file.name.split('.').pop().toLowerCase();
        if (!fileType.includes(ext)) {
          wx.showToast({ title: `请上传${fileType.join('/')}格式文件`, icon: 'none' });
          callback(false);
          return;
        }
      }
      
      // 文件名特殊字符校验
      if (file.name.includes(',')) {
        wx.showToast({ title: '文件名不能包含逗号', icon: 'none' });
        callback(false);
        return;
      }
      
      // 文件大小校验
      const maxSizeMB = fileSize * 1024 * 1024;
      if (file.size > maxSizeMB) {
        wx.showToast({ title: `文件大小不能超过${fileSize}MB`, icon: 'none' });
        callback(false);
        return;
      }
      
      wx.showLoading({ title: '上传中...', mask: true });
      callback(true);
    },

    // 文件读取后的上传
    afterRead(event) {
      const { file } = event.detail;
      const { uploadFileUrl, headers, data } = this.data;
      
      wx.uploadFile({
        url: uploadFileUrl,
        filePath: file.path,
        name: 'file',
        header: headers,
        formData: data,
        success: (res) => {
          wx.hideLoading();
          const response = JSON.parse(res.data);
          if (response.code === 200) {
            this.handleUploadSuccess(response, file);
          } else {
            this.handleUploadError(response.msg);
          }
        },
        fail: (err) => {
          wx.hideLoading();
          this.handleUploadError('上传失败');
        }
      });
    },

    // 处理上传成功
    handleUploadSuccess(response, file) {
      const newFile = {
        ...file,
        url: response.fileName,
        status: 'done',
        message: '上传成功'
      };
      
      const fileList = [...this.data.fileList, newFile];
      this.setData({ fileList });
      this.triggerEvent('update', { value: fileList.map(f => f.url).join(',') });
      wx.showToast({ title: '上传成功', icon: 'success' });
    },

    // 处理上传错误
    handleUploadError(msg) {
      wx.showToast({ title: msg || '上传失败', icon: 'none' });
    },

    // 删除文件
    handleDelete(event) {
      const { index } = event.detail;
      const fileList = this.data.fileList.filter((_, i) => i !== index);
      this.setData({ fileList });
      this.triggerEvent('update', { value: fileList.map(f => f.url).join(',') });
    },

    // 文件大小超出限制
    handleOversize() {
      wx.showToast({ 
        title: `文件大小不能超过${this.properties.fileSize}MB`, 
        icon: 'none' 
      });
    },

    // 预览文件
    handlePreview(event) {
      const { index } = event.detail;
      const file = this.data.fileList[index];
      wx.downloadFile({
        url: this.data.baseUrl + file.url,
        success: (res) => {
          wx.openDocument({
            filePath: res.tempFilePath,
            showMenu: true,
          });
        }
      });
    }
  }
});